package com.qumitech.visualnovel.service.withdraw.impl;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.withdraw.WithdrawRuleConfigNewDTO;
import com.qumitech.visualnovel.service.withdraw.WithdrawRuleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WithdrawRuleServiceImpl implements WithdrawRuleService {
    private static final String WITHDRAW_RULE_URL = "/admin/withdraw/rule";

    @Override
    public BaseRsp listWithdrawRuleConfig(Map<String, Object> reqMap) {
        String url = UrlConstant.SERVER_URL + WITHDRAW_RULE_URL + "/config";
        String body = HttpInvokeUtil.httpGet(url, reqMap);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp addWithdrawRuleConfig(WithdrawRuleConfigNewDTO dto) {
        String url = UrlConstant.SERVER_URL + WITHDRAW_RULE_URL + "/config";
        dto.setOperator(getActiveUserName());
        String body = HttpInvokeUtil.httpPostJson(url, JSONObject.toJSONString(dto), UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp deleteWithdrawRuleConfig(String cfgId) {
        String url = UrlConstant.SERVER_URL + WITHDRAW_RULE_URL + "/config/" + cfgId;
        Map<String, String> headers = new HashMap<>();
        headers.put("operator", getActiveUserName());
        String body = HttpInvokeUtil.httpDelete(url, headers);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    private String getActiveUserName() {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return activeUser.getUsername();
    }
}
